package com.beemans.corekit.integration.admob;

import android.os.Handler;
import android.os.Looper;

import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.Timer;
import java.util.TimerTask;

public abstract class AbBaseAdvert {
    protected final Handler timeoutHandler = new Handler(Looper.getMainLooper());

    @Nullable
    private Timer waitTimer;
    @Nullable
    private Runnable timeoutRunnable;

    /**
     * @return 广告是否准备完毕
     */
    public abstract boolean isAdvertReady();

    /**
     * @return 广告是否正在加载
     */
    public abstract boolean isAdvertLoading();

    /**
     * 广告加载
     */
    protected abstract void loadAdvert();

    /**
     * 广告释放
     */
    @CallSuper
    public void onAdvertRelease() {
        clearTimeout();
        stopWaitTimer();
    }

    /**
     * 设置超时
     *
     * @param delayMillis 超时时间戳
     * @param runnable    超时回调
     */
    protected void setTimeout(long delayMillis, @NonNull Runnable runnable) {
        if (delayMillis > 0) {
            timeoutRunnable = runnable;
            timeoutHandler.postDelayed(timeoutRunnable, delayMillis);
        }
    }

    /**
     * 清除超时设定
     */
    protected void clearTimeout() {
        if (timeoutRunnable != null) {
            if (timeoutHandler.hasCallbacks(timeoutRunnable)) {
                timeoutHandler.removeCallbacks(timeoutRunnable);
            }
            timeoutRunnable = null;
        }
    }

    /**
     * 等待广告加载
     *
     * @param runnable 广告加载结束回调
     */
    protected void waitForAdvertToLoad(@NonNull Runnable runnable) {
        if (!isAdvertLoading()) {
            runnable.run();
            return;
        }
        startWaitTimer(() -> {
            if (isAdvertLoading()) {
                return;
            }

            stopWaitTimer();
            runnable.run();
        });
    }

    private void startWaitTimer(@NonNull Runnable runnable) {
        if (waitTimer == null) {
            waitTimer = new Timer();
            waitTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    AdvertThreadUtils.runOnUiThread(runnable);
                }
            }, 1000, 500);
        }
    }

    private void stopWaitTimer() {
        if (waitTimer != null) {
            waitTimer.cancel();
            waitTimer = null;
        }
    }
}